//利用原生node实现一个路由跳转

const Koa = require('koa');
const app = new Koa();
const fs = require('fs');

//根据路径找到文件读取
function render (url) {
    return new Promise ( (resolve,reject) => {
        const pageUrl = `./page/${url}`;
        fs.readFile(pageUrl,'utf8',(err,data) => {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        });
    }); 
}

//根据url找到html文件
async function route (url) {
    let pageUrl = '404.html';
    switch (url) {
        case '/':
            pageUrl = 'index.html';
            break;
        case '/index':
            pageUrl = 'index.html';
            break;
        case '/todo':
            pageUrl = 'todo.html';
            break;
        default:
            break;
    }
    const html = render(pageUrl);
    return html;
}

app.use(async ctx => {
    const url = ctx.request.url;//获取地址
    const html = await route(url);//根据地址获取相应html文件路径并读取
    ctx.body = html;//页面显示
});

app.listen(3000, () => {
    console.log('[Server] is running at port 3000.');
});